package com.atguigu.gulimall.seckill.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.mq.SeckillOrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.seckill.feign.CouponFeignService;
import com.atguigu.gulimall.seckill.feign.ProductFeignService;
import com.atguigu.gulimall.seckill.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.seckill.service.SeckillService;
import com.atguigu.gulimall.seckill.to.SeckillSkuRedisTo;
import com.atguigu.gulimall.seckill.vo.SeckillSessionWithSkus;
import com.atguigu.gulimall.seckill.vo.SkuInfoVo;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @Author : Jungle
 * @Description :
 */
@Slf4j
@Service
public class SeckillServiceImpl implements SeckillService {
    @Autowired
    private CouponFeignService couponFeignService;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    public static final String SESSIONS_CACHE_PREFIX = "seckill:sessions:";
    public static final String SKUKILL_CACHE_PREFIX = "seckill:skus";
    /**
     * 库存信号量
     */
    public static final String SKU_STOCK_SEMAPHORE = "seckill:stock:"; //加商品随机码

    @Override
    public void uploadSeckillSkuLast3Day() {
        //1、扫描最近三天需要参与秒杀的活动
        R r = couponFeignService.getLatest3DaySession();
        if (r.getCode() == 0) {
            //上架商品
            List<SeckillSessionWithSkus> sessionData = r.getData(new TypeReference<List<SeckillSessionWithSkus>>() {
            });
            if (sessionData != null && sessionData.size() > 0) {
                //1、缓存活动信息
                saveSessionInfos(sessionData);
                //2、缓存活动的关联信息
                saveSessionSkuInfos(sessionData);
            }

        }

    }


    /**
     * 1、getCurrentSeckillSkus 的降级处理方法
     * 返回值 参数需要一样， 参数多一个BlockException
     *
     * blockHandler 函数会在原方法被限流/降级/系统保护的时候调用，而 fallback 函数会针对所有类型的异常
     */
    public List<SeckillSkuRedisTo> blockHandler(BlockException e){
        log.info("getCurrentSeckillSkusResource被限流了==>{}",e.getMessage());
        return null;
    }
    /**
     * 返回当前时间可以参与秒杀的商品信息
     */
    @SentinelResource(value = "getCurrentSeckillSkusResource",blockHandler = "blockHandler")
    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
        //1、确定当前时间属于哪个场次
        //1970 -当前时间间隔
        long time = System.currentTimeMillis();
        try (Entry entry=SphU.entry("seckillSkus")){
            Set<String> keys = stringRedisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");

            for (String key : keys) {
                //seckill:sessions:1648310400000_1648317600000
                String replace = key.replace(SESSIONS_CACHE_PREFIX, "");
                //得到时间区间
                String[] s = replace.split("_");
                long start = Long.parseLong(s[0]);
                long end = Long.parseLong(s[1]);
                if (time >= start && time <= end) {
                    //2、获取整个秒杀场次所需要的商品信息
                    List<String> range = stringRedisTemplate.opsForList().range(key, -100, 100);
                    //跳出循环  强制约束成String类型
                    BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                    //这里需要一个集合，要指定类型
                    List<String> list = hashOps.multiGet(range);
                    if (list != null && list.size() > 0) {
                        List<SeckillSkuRedisTo> collect = list.stream().map((item) -> {
                            SeckillSkuRedisTo redisTo = JSON.parseObject((String) item, SeckillSkuRedisTo.class);
                            //redisTo.setRandomCode(null);  当前秒杀开始了需要随机码
                            return redisTo;
                        }).collect(Collectors.toList());
                        return collect;
                    }
                    break;

                }

            }
        } catch (BlockException  e) {
           log.info("资源呗限流==>{}",e.getMessage());
        }


        return null;
    }


    @Override
    public SeckillSkuRedisTo getSkuSeckillInfo(Long skuId) {
        //找到所有需要参与秒杀的商品的key
        BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        //查出所所有session_skuId集合
        Set<String> keys = hashOps.keys();
        String regx = "\\d_" + skuId;
        if (keys != null && keys.size() > 0) {
            for (String key : keys) {
                if (Pattern.matches(regx, key)) {
                    String json = hashOps.get(key);
                    SeckillSkuRedisTo redisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);
                    long current = System.currentTimeMillis();
                    //处理随机码， 只能在秒杀有效期内显示
                    if (current >= redisTo.getStartTime() && current <= redisTo.getEndTime()) {

                    } else {
                        redisTo.setRandomCode(null);
                    }
                    return redisTo;
                }
            }

        }
        return null;
    }

    /**
     * 秒杀
     *
     * @param killId 7_3 前端传过来
     * @param key
     * @param num
     * @return
     */
    // TODO: 2022/3/31 上架秒杀的商品，每一个都有过期时间
    // TODO: 2022/3/31 秒杀后续的流程，简化了收货的信息
    @Override
    public String kill(String killId, String key, Integer num) {
        Instant s1 = Instant.now();
        MemberRespVo respVo = LoginUserInterceptor.loginUser.get();
        //1、获取当前钱秒杀商品的详细信息
        BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String json = hashOps.get(killId);
        if (StringUtils.isEmpty(json)) {
            return null;
        } else {
            SeckillSkuRedisTo redisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);
            //  校验合法性
            //    1、校验时间的合法性
            Long startTime = redisTo.getStartTime();
            Long endTime = redisTo.getEndTime();
            long time = System.currentTimeMillis();
            if (time >= startTime && time <= endTime) {
                //2、校验随机码和商品id
                String randomCode = redisTo.getRandomCode();
                String skuId = redisTo.getPromotionSessionId() + "_" + redisTo.getSkuId();
                //随机码和商品id相等
                if (randomCode.equals(key) && killId.equals(skuId)) {
                    //3、验证购物数量是否合理
                    if (num <= redisTo.getSeckillLimit()) {
                        //4、验证这个人是否已经购买过  幂等性；如果只要秒杀成功就去占位。userId_SessionId_skuId
                        //SETNX
                        String redisKey = respVo.getId() + "_" + skuId;
                        //设置自动过期时间
                        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), endTime - startTime, TimeUnit.MILLISECONDS);
                        if (aBoolean) {
                            //占位成功，说明从来没有买过
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                            //从信号量中取出一定个数
                            try {
                                boolean b = semaphore.tryAcquire(num, 10, TimeUnit.MILLISECONDS);
                                if (b) {
                                    //秒杀成功
                                    //快速下单  发送MQ消息， 10ms
                                    //返回订单号
                                    String orderSn = IdWorker.getTimeId();
                                    SeckillOrderTo orderTo = new SeckillOrderTo();
                                    orderTo.setOrderSn(orderSn)
                                            .setMemberId(respVo.getId())
                                            .setPromotionSessionId(redisTo.getPromotionSessionId())
                                            .setNum(num)
                                            .setSkuId(redisTo.getSkuId())
                                            .setSeckillPrice(redisTo.getSeckillPrice());

                                    //String exchange, String routingKey, final Object object
                                    rabbitTemplate.convertAndSend("order-event-exchange","order.seckill.order",orderTo);
                                    Instant s2 = Instant.now();
                                    log.info("耗时==>{}", Duration.between(s1,s2).toMillis());
                                    return orderSn;
                                }
                                return null;

                            } catch (InterruptedException e) {
                                return null;
                            }
                        } else {
                            //占位失败，说明已经买过了
                        }
                    }
                }
            } else {
                return null;
            }
        }

        return null;
    }

    private void saveSessionInfos(List<SeckillSessionWithSkus> sessionData) {
        if (!CollectionUtils.isEmpty(sessionData)) {
            sessionData.stream().forEach(session -> {
                //转成long型方便比较
                Long startTime = session.getStartTime().getTime();
                Long endTime = session.getEndTime().getTime();
                String key = SESSIONS_CACHE_PREFIX + startTime + "_" + endTime;
                //缓存活动信息
                Boolean hasKey = stringRedisTemplate.hasKey(key);
                //没有这个key的数据才进行操作
                if (!hasKey) {
                    //保存redis,保存集合
                    //收集关联商品的skuId
                    if (!CollectionUtils.isEmpty(session.getRelationSkus())) {
                        List<String> collect = session.getRelationSkus().stream().map(item -> item.getPromotionSessionId().toString() + "_" + item.getSkuId().toString()).collect(Collectors.toList());
                        stringRedisTemplate.opsForList().leftPushAll(key, collect);
                    }
                }
            });
        }
    }

    private void saveSessionSkuInfos(List<SeckillSessionWithSkus> sessionData) {
        sessionData.stream().forEach(session -> {
            //1、准备hash操作
            BoundHashOperations<String, Object, Object> ops = stringRedisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
            session.getRelationSkus().stream().forEach(seckillSkuVo -> {
                String token = IdUtil.fastSimpleUUID();
                //定义key为活动场次id+商品skuId  这里key要求字符串
                String key = seckillSkuVo.getPromotionSessionId() + "_" + seckillSkuVo.getSkuId();
                if (!ops.hasKey(key)) {
                    //  缓存商品
                    SeckillSkuRedisTo redisTo = new SeckillSkuRedisTo();
                    //    1、sku的基本
                    R skuInfo = productFeignService.getSkuInfo(seckillSkuVo.getSkuId());
                    if (skuInfo.getCode() == 0) {
                        //远程调用先要判断是否成功
                        SkuInfoVo info = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                        //1、保存基本信息
                        redisTo.setSkuInfo(info);
                    }
                    // 2.保存sku秒杀信息
                    BeanUtils.copyProperties(seckillSkuVo, redisTo);
                    //3、设置上架商品的秒杀时间信息
                    redisTo.setStartTime(session.getStartTime().getTime());
                    redisTo.setEndTime(session.getEndTime().getTime());
                    // 4、随机码?  为了保证不被攻击  seckiLL?skuId=1&key=dadlajldj;
                    redisTo.setRandomCode(token);


                    String jsonString = JSON.toJSONString(redisTo);
                    ops.put(key, jsonString);

                    //如果当前这个场次的商品信息已经上架了就不需要再上架了
                    //5、使用库存作为分布式信号量  限流
                    String semKey = SKU_STOCK_SEMAPHORE + token;
                    RSemaphore semaphore = redissonClient.getSemaphore(semKey);
                    //商品可以秒杀的数量作为信号量
                    semaphore.trySetPermits(seckillSkuVo.getSeckillCount());
                    //没有数据执行下面
                }
            });
        });
    }


}
